<?php
namespace app\command;

use app\model\OrderLogisticsModel;
use app\model\OrdersModel;
use app\model\StatisticsModel;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Db;

class AutoConfirmSign extends Command
{

    protected function configure()
    {
        $this->setName('自动确认签收')
            ->setDescription('批量处理订单自动确认签收');
    }

    protected function execute(Input $input, Output $output)
    {

        $orderModel = new OrdersModel();
        $orderLogisticsModel = new OrderLogisticsModel();
        //把已经满足自动签收的单子自动签收了
        $where =[];
        $where[] = ["order_status","IN",[1,2,3]];
        $where[] = ["is_delete","=","0"];
        $where[] = ["auto_sign_time",'<=', date("Y-m-d H:i:s")];
        $list =   Db::name('orders')
            ->alias("o")
            ->field("o.order_id")
            ->where($where)
            ->select();
        if($list){
            foreach ($list as $one){
                $res = $orderModel->updateAll(["order_id"=>$one["order_id"]],['order_status'=>4]);
                if($res){
                    $orderModel->delCache($one["order_id"]);
                }
            }
        }

        //计算预计自动签收时间
        $where =[];
        $where[] = ["o.order_status","IN",[1,2,3]];
        $where[] = ["o.is_delete","=","0"];
        $where[] = ["o.auto_sign_time","=",null];
        $list =   Db::name('orders')
            ->alias("o")
            ->field("o.order_id")
            ->where($where)
            ->select();
        if($list) {
            foreach ($list as $one){
                $map = [];
                $map[] = ["order_id","=",$one["order_id"]];
                $map[] = ["is_delete","=","0"];
                //可能会有多个包裹
                $logisticsList = $orderLogisticsModel->getList($map);
                if($logisticsList){
                    $signNum = 0;
                    $min_sign_time = "";
                    foreach ($logisticsList as $lo){
                        if($lo["logistics_status"] == 300003){
                            $signNum ++;
                            if(empty($min_sign_time)){
                                $min_sign_time = $lo["updated_at"];
                            }elseif (strtotime($min_sign_time) > strtotime($lo["updated_at"])){
                                $min_sign_time = $lo["updated_at"];
                            }
                        }
                    }
                    //如果包裹全部签收了,就更新预计自动签收时间
                    if($signNum == count($logisticsList) && !empty($min_sign_time)){
                        $orderModel->updateOrderAutoSignTime($one["order_id"],date("Y-m-d H:i:s",strtotime($min_sign_time) + 3 * 24 * 3600 ));
                        $orderModel->delCache($one["order_id"]);
                    }
                }
            }
        }
    }
}